<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix"></image>
      <text class="title">司机登录</text>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
          <view class="iconfont icon-user icon"></view>
          <input v-model="loginForm.phonenumber" class="input" type="number" placeholder="请输入手机号" maxlength="11" />
        </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="6" />
        <button @click="sendCode" class="send-code-btn" :disabled="sendDisabled">{{ sendText }}</button>
      </view>
      <view class="action-btn">
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
      </view>
      <view class="xieyi text-center">
        <text class="text-grey1">登录即代表同意</text>
        <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
  import { driverLogin, sendCode } from '@/api/login'
import { getToken, setToken } from '@/utils/auth'
import request from '@/utils/request'

  export default {
    data() {
      return {
        globalConfig: getApp().globalData.config,
        loginForm: {
          phonenumber: "",
          code: ""
        },
        sendDisabled: false,
        sendText: "发送验证码",
        countdown: 60
      }
    },
    onLoad() {
      //#ifdef H5
      // 司机登录页面不自动跳转，允许用户切换身份登录
      // if (getToken()) {
      //   this.$tab.reLaunch('/pages/index')
      // }
      //#endif
    },
    methods: {
      // 隐私协议
      handlePrivacy() {
        let site = this.globalConfig.appInfo.agreements[0]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 用户协议
      handleUserAgrement() {
        let site = this.globalConfig.appInfo.agreements[1]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 发送验证码
      sendCode() {
        if (this.loginForm.phonenumber === "") {
          this.$modal.msgError("请输入手机号")
          return
        }
        if (!/^1[3-9]\d{9}$/.test(this.loginForm.phonenumber)) {
          this.$modal.msgError("请输入正确的手机号")
          return
        }

        this.sendDisabled = true
        this.sendText = `${this.countdown}秒后重新发送`

        console.log('开始发送验证码...');
        console.log('手机号:', this.loginForm.phonenumber);
        
        // 使用api/login.js中定义的sendCode函数发送验证码
        sendCode(this.loginForm.phonenumber).then(response => {
          console.log('验证码发送成功响应:', response);
          // 直接显示验证码在弹窗中 - 确保正确获取验证码数据
          let verificationCode = '未知';
          
          // 由于request.js直接返回了res.data，所以response就是返回的数据对象
          if (response && response.code === 200) {
            // 检查返回的数据结构并获取验证码
            if (response.msg && typeof response.msg === 'string') {
              // 尝试从msg中提取4位数字验证码
              const msgCodeMatch = response.msg.match(/\d{4}/);
              if (msgCodeMatch) {
                verificationCode = msgCodeMatch[0];
              } else {
                verificationCode = response.msg;
              }
            } else if (response.data) {
              verificationCode = response.data;
            } else {
              verificationCode = JSON.stringify(response);
            }
          } else {
            verificationCode = JSON.stringify(response);
          }
          
          this.$modal.alert(`验证码：${verificationCode}`, '验证码已生成');
          
          let timer = setInterval(() => {
            this.countdown--
            this.sendText = `${this.countdown}秒后重新发送`
            if (this.countdown <= 0) {
              clearInterval(timer)
              this.sendDisabled = false
              this.sendText = "发送验证码"
              this.countdown = 60
            }
          }, 1000)
        }).catch(error => {
          console.error('发送验证码失败:', error);
          this.sendDisabled = false
          this.sendText = "发送验证码"
          this.$modal.msgError(error.msg || "验证码发送失败")
        })
      },
      // 登录方法
      async handleLogin() {
        if (this.loginForm.phonenumber === "") {
          this.$modal.msgError("请输入手机号")
        } else if (this.loginForm.code === "") {
          this.$modal.msgError("请输入验证码")
        } else {
          try {
            // 只传递API定义中需要的两个参数
            const res = await driverLogin(
              this.loginForm.phonenumber,
              this.loginForm.code
            )
            console.log('登录成功响应:', res);
            
            // 登录成功，保存token到本地存储和Vuex store
            // 检查返回的数据结构，根据实际情况获取token
            if (res && res.data && res.data.access_token) {
              // 如果返回了access_token字段
              await this.$store.commit('SET_TOKEN', res.data.access_token)
              await setToken(res.data.access_token)
            } else if (res && res.data) {
              // 如果直接返回token
              await this.$store.commit('SET_TOKEN', res.data)
              await setToken(res.data)
            }
            
            // 跳转到首页tab
            // 使用switchTab跳转到tabBar页面，而不是reLaunch
            uni.switchTab({ url: '/pages/index' })
          } catch (error) {
            console.error('登录失败:', error);
            this.$modal.msgError(error.msg || "登录失败")
          }
        }
      }
    }
  }
</script>

<style scoped>
  .normal-login-container {
    padding: 80rpx 40rpx 40rpx 40rpx;
    box-sizing: border-box;
    height: 100vh;
    background-color: #f5f5f5;
  }

  .logo-content {
    margin-bottom: 60rpx;
  }

  .title {
    margin-left: 20rpx;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .login-form-content {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  }

  .input-item {
    border-bottom: 1rpx solid #eee;
    padding: 20rpx 0;
    margin-bottom: 30rpx;
  }

  .icon {
    font-size: 32rpx;
    color: #999;
    margin-right: 20rpx;
  }

  .input {
    flex: 1;
    font-size: 30rpx;
    color: #333;
  }

  .send-code-btn {
    width: 180rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    font-size: 26rpx;
    color: #1989fa;
    background-color: transparent;
    border: none;
    padding: 0;
    margin-left: 20rpx;
  }

  .send-code-btn:disabled {
    color: #c0c4cc;
  }

  .action-btn {
    margin-top: 60rpx;
  }

  .login-btn {
    background-color: #1989fa;
    color: #fff;
  }

  .reg,
  .xieyi {
    margin-top: 30rpx;
    font-size: 26rpx;
  }

  .text-grey1 {
    color: #999;
  }

  .text-blue {
    color: #1989fa;
    margin: 0 10rpx;
  }
</style>